# 用户控制器
from flask import Blueprint, request, jsonify
from service.user import UserService
from common.response import APIResponse

res = APIResponse()

# 创建蓝图
user_bp = Blueprint('user', __name__, url_prefix='/users')

@user_bp.route('/list', methods=['GET'])
def get_user():
    # 获取单个用户或所有用户
    user_id = request.args.get('id')
    if user_id:
        return UserService.get_user_by_id(user_id)
    else:
        return UserService.get_all_users(request.args)

@user_bp.route('/add', methods=['POST'])
def create_user():
    # 创建新用户
    # data = request.get_json()
    # print(data)
    data = request.get_json() or {} 
    print(data)
    if not data:
        return res.validate_error('请提供用户信息')
    return UserService.create_user(data)

@user_bp.route('/update', methods=['POST'])
def update_user():
    # 更新用户
    # data = request.get_json()
    data = request.get_json() or {} 
    if not data or 'id' not in data:
        return res.validate_error('请提供用户ID')
    user_id = data.pop('id')
    return UserService.update_user(user_id, data)

# 用户登录
@user_bp.route('/login', methods=['POST'])
def login_user():
    # 登录用户
    data = request.get_json() or {} 
    if not data or 'name' not in data or 'password' not in data:
        return res.validate_error('请提供用户名和密码')
    return UserService.login_user(data)
